package com.springboot.tools.handler;

import java.util.Set;
import java.util.logging.Logger;

import com.springboot.tools.mapper.AutoMapper;
import com.springboot.tools.mapper.AutoSqlInjector;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;


public class MybatisConfiguration extends Configuration
{

    protected final Logger logger = Logger.getLogger("MybatisConfiguration");

    public MybatisConfiguration()
    {
        System.err.println("mybatis-plus init success.");
    }


    @Override
    public void addMappedStatement(MappedStatement ms)
    {
        if (this.mappedStatements.containsKey(ms.getId()))
        {

            logger.severe("mapper[" + ms.getId()
                    + "] is ignored, because it's exists, maybe from xml file");
            return;
        }
        super.addMappedStatement(ms);
    }

    @Override
    public LanguageDriver getDefaultScriptingLanuageInstance()
    {

        return languageRegistry.getDriver(MybatisXMLLanguageDriver.class);
    }

    @Override
    public <T> T getMapper(Class<T> type, SqlSession sqlSession)
    {
        return super.getMapper(type, sqlSession);
    }

    @Override
    public <T> void addMapper(Class<T> type)
    {
        super.addMapper(type);

        if (!AutoMapper.class.isAssignableFrom(type))
        {
            return;
        }

        new AutoSqlInjector(this).inject(type);
    }

    @Override
    public void addMappers(String packageName)
    {
        this.addMappers(packageName, Object.class);
    }

    @Override
    public void addMappers(String packageName, Class<?> superType)
    {
        ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
        resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
        Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
        for (Class<?> mapperClass : mapperSet)
        {
            this.addMapper(mapperClass);
        }
    }
}
